import { Injectable } from '@angular/core';
import { Headers, Http, Jsonp } from '@angular/http';
import 'rxjs/add/operator/toPromise';

declare let EventRegistHandle: any;
@Injectable()
export class ServiceBase {
    get SSL(): boolean {
        if (location.protocol.indexOf("https") > -1) {
            return true;
        } else {
            return false;
        }
    }
    get Host(): string {
        let ip = this.HostIp;
        let r = "http://" + ip;
        if (this.SSL) r = "https://" + ip;
        return r;
    }
    get HostIp(): string {
        if (this.LDCAddress) return this.LDCAddress;
        else return null;
    }
    get Port(): number { return this.SSL ? 8886 : 8887; }
    get HostName(): string { return this.Host + ":" + this.Port + "/"; }
    get CloudHost(): string {
        let pro = "http://";
        if (this.SSL) {
            pro = "https://";
        }
        return (pro + "app.menpuji.com");
    }
    get CloudPort(): number {
        return this.SSL ? 443 : 80;
    }
    get CloudHostName(): string {
        let address = localStorage.getItem("cloudAddress")
        if (address) {
            return address;
        }
        return this.CloudHost + ":" + this.CloudPort + "/";
    }

    get CloudClerkAddress(): string {
        let pro = "http://";
        if (this.SSL) {
            pro = "https://";
        }
        return pro + "clerk.menpuji.com";
    }

    set CurrentStore(store: store) {
        localStorage.setItem("store", JSON.stringify(store));
    }
    get CurrentStore(): store {
        let store = localStorage.getItem("store");
        if (store) {
            return JSON.parse(store);
        }
        return null;
    }
    /**
     * 当前店长用户
     */
    set StoreOwner(value) {
        localStorage.setItem("StoreOwner", JSON.stringify(value));
    };
    /**
     * 当前店长用户
     */
    get StoreOwner() {
        let r = localStorage.getItem("StoreOwner");
        if (r) return JSON.parse(r);
        return null;
    }
    set Token(value) {
        localStorage.setItem("token", value);
    }
    get Token() {
        return localStorage.getItem("token");
    }

    set Terminal(value) {
        localStorage.setItem("terminal", JSON.stringify(value));
    }
    get Terminal() {
        let terminal = localStorage.getItem("terminal");
        if (terminal) {
            return JSON.parse(terminal);
        } else {
            return null;
        }
    }

    get Device() {
        let deviceInfo = null;
        if ((<any>window).device) {
            let device = (<any>window).device;
            deviceInfo = device.getDeviceInfo();
        }
        return deviceInfo;
    }

    //当前店员用户
    get CurrentUser() {
        let user = localStorage.getItem("currentUser");
        if (user) {
            return JSON.parse(user);
        }
        return null;
    }

    set CurrentUser(user) {
        localStorage.setItem("currentUser", JSON.stringify(user));
    }

    get LDCConfig() {
        let config = localStorage.getItem("ldcconfig");
        if (config) {
            return JSON.parse(config);
        }
        return null;
    }
    set LDCConfig(value) {
        localStorage.setItem("ldcconfig", JSON.stringify(value));
    }

    /**
     * 本地数据中心地址
    */
    set LDCAddress(ip: string) {
        localStorage.setItem("LDCAddress", ip);
    }

    get LDCAddress() {
        return localStorage.getItem("LDCAddress");
    }

    // 店员登录用户列表
    set RememberList(rememberList) {
        localStorage.setItem("rememberList", JSON.stringify(rememberList));
    }
    get RememberList() {
        let rememberList = localStorage.getItem("rememberList");
        if (rememberList) {
            return JSON.parse(rememberList);
        } else {
            return [];
        }
    }

    protected http: Http;
    protected jsonp: Jsonp;

    /**
     * 
     * @param url 请求地址
     * @param params
     * @param sucb
     * @param errcb
     */
    protected Post(url: string, params) {
        url = this.HostName + url;
        let headers = new Headers();
        if (this.CurrentStore)
            headers.append("storeId", this.CurrentStore.id);
        return this.doPost(url, params, headers);
    }
    /**
     * @param  {string} url
     * @param  {} params 
     */
    protected PostCloud(url: string, params) {
        url = this.CloudHostName + url;
        let headers = new Headers();
        headers.append("boundApp", "mclerk");
        return this.doPost(url, params, headers);
    }

    protected GetCloud(url: string) {
        url = this.CloudHostName + url;
        let result;
        result = (this.http.get(url) as any).toPromise();
        return this.ResultCallback(result);
    }

    private doPost(url: string, params, headers: Headers) {
        let result;
        headers.append("Content-Type", "application/json");
        if (this.Token)
            headers.append("token", this.Token);
        if (this.Terminal) {
            params.user = this.CurrentUser;
            params.terminal = this.Terminal;
        }
        result = (<any>this.http.post(url, JSON.stringify(params), { headers: headers })).toPromise();
        return this.ResultCallback(result);
    }

    /**
     * 
     * @param url
     * @param sucb
     * @param errcb
     */
    protected Get(url: string, hostName?: string, port?: number) {
        let result;
        if (hostName) {
            hostName = this.SSL ? "https://" + hostName : "http://" + hostName;
        }
        let host = hostName ? hostName : this.Host;
        let p = port ? port : this.Port;
        url = host + ":" + p + "/" + url;

        result = (this.http.get(url) as any).toPromise();
        return this.ResultCallback(result);
    }
    /**
     * 
     * @param url
     * @param params
     * @param sucb
     * @param errcb
     */
    protected Put(url: string, params): Promise<any> {
        let result;
        url = this.HostName + url;
        let headers = new Headers();
        headers.append("Content-Type", "application/json");
        headers.append("token", this.Token);
        headers.append("storeId", this.CurrentStore.id);
        if (this.Terminal) {
            params.user = this.CurrentUser;
            params.terminal = this.Terminal;
        }
        result = (<any>this.http.put(url, JSON.stringify(params), { headers: headers })).toPromise();

        return this.ResultCallback(result);
    }

    protected PutCloud(url: string, params) {
        url = this.CloudHostName + url;
        let headers = new Headers();
        headers.append("Content-Type", "application/json");
        headers.append("token", this.Token);
        headers.append("storeId", this.CurrentStore.id);
        let result = (<any>this.http.put(url, JSON.stringify(params), { headers: headers })).toPromise();
        return this.ResultCallback(result);
    }

    protected Jsonp(url: string, params) {
        url = this.CloudHostName + url;
        (<any>this.jsonp.get(url, { search: params })).toPromise();

        return new Promise((resolve, reject) => {
            EventRegistHandle.RegistHandle("jsonpHandle", (data) => {
                EventRegistHandle.RemoveHandle("jsonpHandle");
                if (data.result != undefined && data.result == false) {
                    reject(data.msg);
                }
                else {
                    resolve(data);
                }

            });
        });
    }

    private ResultCallback(result): Promise<any> {
        return new Promise((resolve, reject) => {
            result.then(data => {
                if (data.ok) {
                    let rData = data.json();
                    /*判断rData是否满足标准的格式，如果不是标准的格式
                    * 如果不是标准的格式则是来自数据同步老接口返回
                    */
                    if (this.IsOldAPIResult(rData)) {
                        if (rData.code == 200) resolve(rData.data);
                        else reject(rData.message);
                    }
                    else resolve(rData);
                }
                else reject(data.json().message);
            }).catch(err => {
                console.log(err);
                reject(err);
            })
        });
    }

    private IsOldAPIResult(data): boolean {
        let checkPnts = [false, false, false];
        if (data.code != null && data.code != undefined) checkPnts[0] = true;
        if (data.code) {
            if (data.code == 200) {
                if (data.data) return true;
                else return false;
            }
            else {
                if (data.message) return true;
                else return false;
            }
        }
        else return false;
    }
}

interface store {
    id: string;
    configs?: {
        value;
    };
}